﻿//#define DEBUG
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading.Tasks;
using GanagroLiteBO;
using GLiteInterfaces;
using GeneralUtilities;

namespace GanagroLite
{
    public partial class MainForm : Form,IOperacionView
    {

        private static MainForm _main;

        internal static MainForm Instance
        {
            get { return _main; }
        }

        #region Constructors
         public MainForm()
        {
            InitializeComponent();
            _main = this;
        }
        #endregion

        #region WinPart handling

        /// <summary>
        /// Add a new WinPart control to the
        /// list of available documents and
        /// make it the active WinPart.
        /// </summary>
        /// <param name="part">The WinPart control to add and display.</param>
        private void AddWinPart(WinPart part)
        {
            this.CerrarTodos();
            part.CloseWinPart += new EventHandler(CloseWinPart);
            part.BackColor = toolStrip1.BackColor;
            Panel1.Controls.Add(part);
            ShowWinPart(part);
        }

        /// <summary>
        /// Make the specified WinPart the 
        /// active, displayed control.
        /// </summary>
        /// <param name="part">The WinPart control to display.</param>
        private void ShowWinPart(WinPart part)
        {
            part.Dock = DockStyle.Fill;
            part.Visible = true;
            part.BringToFront();
            this.Text = "Ganagro - " + part.ToString();
        }

        /// <summary>
        /// Populate the Documents dropdown list.
        /// </summary>
        private void DocumentsToolStripDropDownButton_DropDownOpening(
          object sender, EventArgs e)
        {
        }

        /// <summary>
        /// Make selected WinPart the active control.
        /// </summary>
        private void DocumentClick(object sender, EventArgs e)
        {
            WinPart ctl = (WinPart)((ToolStripItem)sender).Tag;
            ShowWinPart(ctl);
        }

        /// <summary>
        /// Gets a count of the number of loaded
        /// documents.
        /// </summary>
        public int DocumentCount
        {
            get
            {
                int count = 0;
                foreach (Control ctl in Panel1.Controls)
                    if (ctl is WinPart)
                        count++;
                return count;
            }
        }

        private void CerrarTodos()
        {
            foreach (Control ctl in Panel1.Controls)
            {
                if (ctl is WinPart)
                {
                    CloseWinPart(ctl, EventArgs.Empty);
                }
            }
        }
        /// <summary>
        /// Handles event from WinPart when that
        /// WinPart is closing.
        /// </summary>
        private void CloseWinPart(object sender, EventArgs e)
        {
            WinPart part = (WinPart)sender;
            part.CloseWinPart -= new EventHandler(CloseWinPart);
            part.Visible = false;
            Panel1.Controls.Remove(part);
            part.Dispose();
            if (DocumentCount == 0)
            {
                this.Text = "Ganagro";
            }
            else
            {
                // Find the first WinPart control and set
                // the main form's Text property accordingly.
                // This works because the first WinPart 
                // is the active one.
                foreach (Control ctl in Panel1.Controls)
                {
                    if (ctl is WinPart)
                    {
                        this.Text = "Ganagro - " + ctl.ToString();
                        break;
                    }
                }
            }
        }

        #endregion

        private void MainForm_Load(object sender, EventArgs e)
        {
            this.toolStripDbName.Text = string.Format("Server: {0}", UtilityDB.GetServerName());
            this.toolStripDbName.ForeColor = Color.Black;
            this.toolStripDbName.Font = new Font(FontFamily.GenericSansSerif,12);
        }

        private void Panel1_Resize(object sender, EventArgs e)
        {
            foreach (Control ctl in Panel1.Controls)
                if (ctl is WinPart)
                    ctl.Size = Panel1.ClientSize;
        }

        #region toolstrip Click events

        private void comprasToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (StatusBusy busy =
              new StatusBusy("Editando compras...",string.Empty))
            {
                AddWinPart(new FormCompras(false));
            }

        }

        private void pesajesDeControlToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (StatusBusy busy =new StatusBusy("Editando semoviente..."))
            {
                AddWinPart(new FormPesajes(false));
            }
        }

        private void cambiarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (StatusBusy busy = new StatusBusy("Cambiando lote de semoviente..."))
            {
                AddWinPart(new CambiarLote());
            }
        }

        private void muerteToolStripMenuItem_Click(object sender, EventArgs e)
        {

            using (StatusBusy busy =
              new StatusBusy("Registro de Muerte..."))
            {
                AddWinPart(new FormMuertes());
            }
        }

        private void salirToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ventasToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (StatusBusy busy =
             new StatusBusy("Editando Ventas..."))
            {
                AddWinPart(new FormVentas(false));
            }

        }

        private void consultasLibresToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (StatusBusy busy =
             new StatusBusy("Cargando Consultas libres..."))
            {
                AddWinPart(new FormConsultasLibres());
            }

        }

        private void reversosToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (StatusBusy busy =
             new StatusBusy("Cargando Reversos..."))
            {
                AddWinPart(new FormReversos());
            }

        }

        private void copiaDeSeguridadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (StatusBusy busy =
             new StatusBusy("Cargando Forma Copias de seguridad..."))
            {
                AddWinPart(new FormBackups());
            }

        }

        private void consultaSemToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (StatusBusy busy =
            new StatusBusy("Cargando Forma Editar semoviente..."))
            {
               AddWinPart(new FormEditarSemoviente(true));
            }
        }

        private void editarSemovienteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (StatusBusy busy =
            new StatusBusy("Editando semoviente..."))
            {
                AddWinPart(new FormEditarSemoviente(false));
            }
        }

        private void manejoDeParametrosToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (StatusBusy busy =
             new StatusBusy("Cargando Forma Parametros..."))
            {
                AddWinPart(new FormParametros());
            }

        }

        private void reportesToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            using (StatusBusy busy =
             new StatusBusy("Cargando Forma Reportes..."))
            {
                AddWinPart(new FormReportes());
            }

        }

        private void marcaCalienteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (StatusBusy busy =
             new StatusBusy("Cargando Forma Asignacion Tatuajes..."))
            {
                AddWinPart(new FormTatuaje());
            }
        }

        private void ToolStripButtonEdSem_Click(object sender, EventArgs e)
        {
            editarSemovienteToolStripMenuItem_Click(this, EventArgs.Empty);
        }

        private void toolStripButtonCompra_Click(object sender, EventArgs e)
        {
            comprasToolStripMenuItem_Click(this, EventArgs.Empty);
        }

        private void toolStripButtonPesaje_Click(object sender, EventArgs e)
        {
            pesajesDeControlToolStripMenuItem_Click(this, EventArgs.Empty);
        }

        private void toolStripButtonVenta_Click(object sender, EventArgs e)
        {
            ventasToolStripMenuItem_Click(this, EventArgs.Empty);
        }

        private void toolStripButtonMuerte_Click(object sender, EventArgs e)
        {
            muerteToolStripMenuItem_Click(this, EventArgs.Empty);
        }

        private void toolStripButtonReportes_Click(object sender, EventArgs e)
        {
            reportesToolStripMenuItem1_Click(this, EventArgs.Empty);
        }

        private void toolStripButtonBackups_Click(object sender, EventArgs e)
        {
            copiaDeSeguridadToolStripMenuItem_Click(this, EventArgs.Empty);
        }

        private void toolStripButtonActividades_Click(object sender, EventArgs e)
        {
        }

        private void toolStripMenuItemcambiarLotes_Click(object sender, EventArgs e)
        {
            cambiarToolStripMenuItem_Click(this, EventArgs.Empty);
        }

        private void toolStripButtonReversos_Click(object sender, EventArgs e)
        {
            reversosToolStripMenuItem_Click(this, EventArgs.Empty);
        }

        private void toolStripMarcaCaliente_Click(object sender, EventArgs e)
        {
            marcaCalienteToolStripMenuItem_Click(this, EventArgs.Empty);
        }

        private void toolStripMenuItemAcercaDe_Click(object sender, EventArgs e)
        {
            using (FormAcercade fde = new FormAcercade())
            {
                fde.ShowDialog();
                
            } 
        }

        #endregion

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        #region IOperacionView Members

        public string status
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                this.StatusLabel1.Text = value;
                this.Update();
            }
        }

        public string status2
        {
            get
            {
                return this.StatusLabel2.Text;
            }
            set
            {
                this.StatusLabel2.Text = value;
                this.Update();
            }
        }

        public void DisplayMessage(string message)
        {
            throw new NotImplementedException();
        }

        public void SetUIBusyStatus()
        {
            this.Cursor = Cursors.WaitCursor;
            this.Update();
        }

        public void SetUIDefaultStatus()
        {
            this.Cursor = Cursors.Default;
            this.Update();
        }

        #endregion

        private void MainForm_Shown(object sender, EventArgs e)
        {
#if DEBUG
            UtilityDB.SetUser("Pedro");
            UtilityDB.SetPwd(File.ReadAllText(@"c:\temp\laclave.txt"));

#else
            Tuple<string, string> promptValues = Prompt.ShowDialog("Logon user / password", "Please provide user and password");
            UtilityDB.SetUser(promptValues.Item1);
            UtilityDB.SetPwd(promptValues.Item2);
#endif

            LoadLookupsAsync();
        }

        static async void LoadLookupsAsync()
        {
            await Task.Run(() => UtilityDB.Loadcolores());
            await Task.Run(() => UtilityDB.Loadestados());
            await Task.Run(() => UtilityDB.Loadrazas());
            await Task.Run(() => UtilityDB.Loadlotes());
        }
    }

    public static class Prompt
        {
        public static Tuple<string, string> ShowDialog(string text, string caption)
        {
            Label textLabel = new Label() { Left = 50, Top = 20, Text = text };
            TextBox textBoxUser = new TextBox() { Left = 50, Top = 50, Width = 100 };
            TextBox textBoxPwd = new TextBox() { Left = 50, Top = 80, Width = 100 };
            Button confirmation = new Button() { Left = 50, Top = 110, Width = 100, Text = "Ok" };
            try
            {
                Form prompt = new Form();
                prompt.Width = 300;
                prompt.Height = 200;
                prompt.FormBorderStyle = FormBorderStyle.FixedDialog;
                prompt.Text = caption;
                prompt.StartPosition = FormStartPosition.CenterScreen;
                confirmation.Click += (sender, e) => { prompt.Close(); };
                prompt.Controls.Add(textBoxUser);
                prompt.Controls.Add(textBoxPwd);
                prompt.Controls.Add(confirmation);
                prompt.Controls.Add(textLabel);
                prompt.AcceptButton = confirmation;
                prompt.ShowDialog();

                var TSS = Tuple.Create(textBoxUser.Text, textBoxPwd.Text);
                return TSS;
            }
            finally
            {
                textLabel.Dispose();
                textBoxUser.Dispose();
                textBoxPwd.Dispose();
                confirmation.Dispose();
            }
        }
        }

}
